﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using D3DSS.FormUI.Properties;

namespace D3DSS.FormUI
{
    /// <summary>
    /// 键盘钩子
    /// </summary>
    public class KeyHook
    {
        [DllImport("user32.dll")]
        private static extern int RegisterHotKey(IntPtr hwnd, int id, int fsModifiers, int vk);
        [DllImport("user32.dll")]
        private static extern int UnregisterHotKey(IntPtr hwnd, int id);

        /// <summary> 
        /// 注册热键 
        /// </summary> 
        /// <param name="hwnd">窗口句柄</param> 
        /// <param name="hotKey_id">热键ID</param> 
        /// <param name="fsModifiers">组合键</param> 
        /// <param name="vk">热键</param> 
        public static void RegKey()
        {
            if (Settings.Default.IsCtrl && !Settings.Default.IsAlt)
            {
                RegKey(Program.MainHandle, Settings.Default.HotKeyID, KeyModifiers.Ctrl, (Keys)(Settings.Default.Shortcuts + Settings.Default.ShortcutsSeed));
            }
            if (!Settings.Default.IsCtrl && Settings.Default.IsAlt)
            {
                RegKey(Program.MainHandle, Settings.Default.HotKeyID, KeyModifiers.Alt, (Keys)(Settings.Default.Shortcuts + Settings.Default.ShortcutsSeed));
            }
            if (Settings.Default.IsCtrl && Settings.Default.IsAlt)
            {
                RegKey(Program.MainHandle, Settings.Default.HotKeyID, KeyModifiers.Ctrl | KeyModifiers.Alt, (Keys)(Settings.Default.Shortcuts + Settings.Default.ShortcutsSeed));
            }
            if (!Settings.Default.IsCtrl && !Settings.Default.IsAlt)
            {
                RegKey(Program.MainHandle, Settings.Default.HotKeyID, KeyModifiers.None, (Keys)(Settings.Default.Shortcuts + Settings.Default.ShortcutsSeed));
            }
        }

        private static void RegKey(IntPtr hwnd, int hotKey_id, KeyModifiers fsModifiers, Keys vk)
        {
            bool result;
            if (RegisterHotKey(hwnd, hotKey_id, (int)fsModifiers, (int)vk) == 0)
            {
                result = false;
            }
            else
            {
                result = true;
            }
            if (!result)
            {
                MessageBox.Show("注册热键失败！");
            }
        }

        /// <summary> 
        /// 注销热键 
        /// </summary> 
        /// <param name="hwnd">窗口句柄</param> 
        /// <param name="hotKey_id">热键ID</param> 
        public static void UnRegKey(IntPtr hwnd, int hotKey_id)
        {
            UnregisterHotKey(hwnd, hotKey_id);
        }
    }

    /// <summary>
    /// 组合键枚举
    /// </summary>
    public enum KeyModifiers
    {
        None = 0,
        Alt = 1,
        Ctrl = 2
    } 
}
